package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.pojo.dto.QueryPageBeanDTO;
import com.itheima.health.pojo.entity.Setmeal;
import com.itheima.health.pojo.result.PageResult;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.service.SetMealService;
import com.itheima.health.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetMealController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private SetMealService setMealService;

    /**
     * 文件上传
     *
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) {
        log.info("文件上传:{}", imgFile);
        try {
            //调用工具类文件上传方法
            //原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            //截取原始文件名的后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String name = UUID.randomUUID() + substring;
            //文件的请求路径
            String url = aliOssUtil.upload(imgFile.getBytes(), name);
            //返回结果
            return new Result(true, MessageConst.UPLOAD_SUCCESS, url);
        } catch (IOException e) {
            log.info("文件上传失败:{}", e.getMessage());
            return new Result(false, e.getMessage());
        }

        //2.返回结果
//        return new Result(true, url);
    }

    /**
     * 新增套餐
     *
     * @param setmeal
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, @RequestParam List<Integer> checkgroupIds) {
        log.info("新增套餐：{},{}", setmeal, checkgroupIds);
        setMealService.add(setmeal, checkgroupIds);
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }

    @GetMapping("/findPage")
    public Result pageQuery(QueryPageBeanDTO queryPageBeanDTO) {
        log.info("分页查询");
        PageResult page = setMealService.pageQuery(queryPageBeanDTO);
        return new Result(true,MessageConst.ADD_SETMEAL_SUCCESS,page);
    }
}
